import 'dart:async';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:get/get.dart';
import 'package:sgy_flutter/ble/ble_manager.dart';
import 'package:sgy_flutter/extensions/get.dart';
import 'package:sgy_flutter/gen/assets.gen.dart';
import 'package:sgy_flutter/model/device_model.dart';
import 'package:sgy_flutter/page/help/view.dart';
import 'package:sgy_flutter/widget/app_bar_x.dart';
import '../home/view/device_model_view.dart';
import 'logic.dart';

class ScanPage extends StatefulWidget {
  const ScanPage({super.key});

  @override
  State<ScanPage> createState() => _ScanPageState();
}

class _ScanPageState extends State<ScanPage> {
  final logic = Get.put(ScanLogic());


  StreamSubscription? _scanningSubscription;

  Timer? _timer;

  BleManager bleManager = Get.find();

  EasyRefreshController _easyRefreshController = EasyRefreshController(
      controlFinishRefresh: true, controlFinishLoad: true);

  @override
  void initState() {
    _scanningSubscription = FlutterBluePlus.isScanning.listen((value) {
      if (value) {
        _easyRefreshController.callRefresh();
        _timer?.cancel();
        _timer = Timer(Duration(seconds: 30), () {
          printInfo(info: "timer call stopScan");
          bleManager.stopScan();
        });
      } else {
        _easyRefreshController.finishRefresh();
      }
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBarX(
          title: Text("设备列表".tr),
          centerTitle: true,
          elevation: 0,
        ),
        body: Column(
          children: [
            Expanded(
              child: EasyRefresh.builder(
                fit: StackFit.expand,
                header: CupertinoHeader(
                    hitOver: true,
                  infiniteHitOver: true,
                  hapticFeedback: true,
                ),
                controller: _easyRefreshController,
                onRefresh: () async{

                  printInfo(info: "triggerWhenRelease");
                  bleManager.scanResults.clear();
                  logic.startScan();
                  // await Future.delayed(Duration(seconds: 20));
                },
                // refreshOnStart: true,
                childBuilder: (BuildContext context, ScrollPhysics physics) {
                  return StreamBuilder(
                    stream: logic.scanResults,
                    builder: (context, snapshot) {
                      final scanResults = snapshot.data ?? [];
                      return _buildContent(scanResults, physics);
                    },
                  );
                },
              ),
            ),
            Ink(
              // color: Colors.red,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // StreamBuilder<bool>(
                  //     initialData: FlutterBluePlus.isScanningNow,
                  //     stream: FlutterBluePlus.isScanning,
                  //     builder: (context, snapshot) {
                  //       return Visibility(
                  //           visible: snapshot.data == true,
                  //           child: SpinKitFadingCircle(
                  //             color: Get.theme.primaryColor,
                  //             size: 30,
                  //           ).marginOnly(bottom: 16));
                  //     }),
                  InkWell(
                    onTap: () => Get.to(() => HelpPage()),
                    child: Text.rich(TextSpan(children: [
                      WidgetSpan(
                          child: Assets.image.iconQuestionBlack
                              .image(width: 16, height: 16)
                              .marginOnly(top: 0, right: 4)),
                      TextSpan(
                          text: "没有发现我的设备 >".tr,
                          style: TextStyle(
                              fontWeight: FontWeight.normal,
                              fontSize: 14,
                              color: Color(0xff7a7a7a))),
                    ])),
                  ).marginOnly(bottom: 16),
                  FilledButton(
                    onPressed: () {
                      bleManager.scanResults.clear();
                      if (!FlutterBluePlus.isScanningNow) {
                        logic.startScan();
                      }
                    },
                    child: Text("重新扫描".tr),
                  ),
                ],
              ).marginOnly(top: 20),
            ).marginOnly(bottom: 16),
          ],
        ));
  }

  Widget _buildContent(List<DeviceModel> scanResults, ScrollPhysics? physics) {
    return CustomScrollView(
      physics: physics,
      slivers: [
        SliverList.builder(
          itemBuilder: (context, index) {
            var model = scanResults[index];
            return DeviceModelView(
              deviceModel: model,
              onConnect: logic.handleDeviceModelTap,
              type: 2,
            ).marginOnly(
                bottom: index == scanResults.length - 1 ? 16 : 0,
                top: index == 0 ? 8 : 0);
          },
          itemCount: scanResults.length,
        ),
      ],
    );
  }

  @override
  void dispose() {
    _timer?.cancel();
    _scanningSubscription?.cancel();
    Get.delete<ScanLogic>();
    super.dispose();
  }
}
